package com.jp.knowledge.logic;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.qiniu.android.common.AutoZone;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.UUID;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by jiayen on 16/12/1.
 * <p>
 * 上传文件操作
 */

public class UploadLogic implements ResultSubscriber.OnResultListener {

    private static DateFormat dataFormat;
    public static String getTime(){
        if(dataFormat == null)
            dataFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return dataFormat.format(System.currentTimeMillis());
    }

    public static String getName(){
        return UUID.randomUUID().toString();
    }

    private final String TAG = "UploadLogic";
    private UploadCallBack  callBack;
    private final int UPLOAD_IMG_CODE = 0x000001;//上传图片

    private Context mContext;
    private String path;
    private String key;

    public UploadLogic(Context context, String path, String key) {
        this.mContext = context;
        this.path = path;
        this.key = key;
    }

    public void setCallBack(UploadCallBack callBack) {
        this.callBack = callBack;
    }


    /**
     * 执行网络上传
     * @param path
     * @param token
     */
    public   void upload(String path, String token) {
        boolean https = true;
        Zone z1 = new AutoZone(/*https, */null);
        Configuration config = new Configuration.Builder().zone(z1).build();
        UploadManager uploadManager = new UploadManager(config);
        File data = new File(path);
        uploadManager.put(data, key, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                //response={"hash":"Flr8KixhqQ50n7wmPocTqIa0xSFq","key":"Flr8KixhqQ50n7wmPocTqIa0xSFq"}
                try {
                    if(response==null)response=info.response;
                    String  url = response.getString("key");
                    if(url!=null){
                        if(callBack!=null)callBack.uploadSuccess(url);
                    }else{
                      ToasUtil.toast(mContext,"上传失败!");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                L.e(TAG, "key=" + key + "======");
                L.e(TAG, "ResponseInfo=====" + info + "======");
                L.e(TAG, "JSONObject=" + response + "======");
            }
        }, null);
    }
    public void uploadImage() {
        JsonObject param = new JsonObject();
        param.addProperty("saveType", 2);
        param.addProperty("key", key);
        HttpHelper.getInstance(mContext).getuploadToken(param, UPLOAD_IMG_CODE, this);
    }

    @Override
    public void onStart(int requestType) {

    }

    @Override
    public void onCompleted(int requestType) {

    }

    @Override
    public void onError(int requestType) {

    }

    @Override
    public void onNext(IModel data, int requestType) {

        if (requestType == UPLOAD_IMG_CODE) {
            String uploadToken = data.getUptoken();
            if(TextUtils.isEmpty(uploadToken))
                uploadToken = ((LinkedTreeMap<String, String>) data.getData()).get("uptoken");
            if (uploadToken == null) {
                ToasUtil.toast(mContext, "获取上传凭证失败");
            } else {
                //执行上传
                handUpload(uploadToken);
            }
        }


    }

    /**
     * 执行上传
     *
     * @param uploadToken
     */
    private void handUpload(final String uploadToken) {
        Observable.create(new Observable.OnSubscribe<Boolean>() {
            @Override
            public void call(Subscriber<? super Boolean> subscriber) {
                try {
                    upload(path, uploadToken);
                    subscriber.onNext(true);
                } catch (Exception e) {
                    subscriber.onError(e);
                }

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Boolean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        if(callBack!=null)
                            callBack.done(false);
                    }

                    @Override
                    public void onNext(Boolean success) {
//                        if(callBack!=null)
//                            callBack.done(success);
                    }
                });
    }

    public interface  UploadCallBack{
        void done(boolean success);
        void uploadSuccess(String  url);
    }
}
